package com.itcaius.weblog.admin.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itcaius.weblog.admin.model.vo.category.AddCategoryReqVO;
import com.itcaius.weblog.admin.model.vo.category.DeleteCategoryReqVO;
import com.itcaius.weblog.admin.model.vo.category.FindCategoryPageListReqVO;
import com.itcaius.weblog.admin.model.vo.category.FindCategoryPageListRspVO;
import com.itcaius.weblog.admin.service.AdminCategoryService;
import com.itcaius.weblog.common.domain.dos.ArticleCategoryRelDO;
import com.itcaius.weblog.common.domain.dos.CategoryDO;
import com.itcaius.weblog.common.domain.mapper.ArticleCategoryRelMapper;
import com.itcaius.weblog.common.domain.mapper.CategoryMapper;
import com.itcaius.weblog.common.enums.ResponseCodeEnum;
import com.itcaius.weblog.common.exception.BizException;
import com.itcaius.weblog.common.model.vo.SelectRspVO;
import com.itcaius.weblog.common.utils.PageResponse;
import com.itcaius.weblog.common.utils.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * @author Caius
 * @description
 * @since Created in 2025-04-23
 */
@Service
@Slf4j
public class AdminCategoryServiceImpl implements AdminCategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private ArticleCategoryRelMapper articleCategoryRelMapper;

    /**
     * 添加分类
     * @param addCategoryReqVO
     * @return
     */
    @Override
    public Response addCategory(AddCategoryReqVO addCategoryReqVO) {
        String categoryName = addCategoryReqVO.getName();

        // 判断是不是已经存在对应的分类
        CategoryDO categoryDO = categoryMapper.selectByName(categoryName);

        if (Objects.nonNull(categoryDO)) {
            log.warn("分类名称： {}，此分类已存在", categoryName);
            throw new BizException(ResponseCodeEnum.CATEGORY_NAME_IS_EXISTED);
        }

        CategoryDO insertCategoryDO = CategoryDO.builder().name(addCategoryReqVO.getName().trim()).build();

        categoryMapper.insert(insertCategoryDO);

        return Response.success();
    }

    /**
     * 分页查找分类数据
     * @param findCategoryPageListReqVO
     * @return
     */
    @Override
    public PageResponse findCategoryList(FindCategoryPageListReqVO findCategoryPageListReqVO) {
        // 获取当前页面和返回的界面数量
        Long current = findCategoryPageListReqVO.getCurrentPage();
        Long size = findCategoryPageListReqVO.getSize();
        String name = findCategoryPageListReqVO.getName();
        LocalDate startTime = findCategoryPageListReqVO.getStartTime();
        LocalDate endTime = findCategoryPageListReqVO.getEndTime();

        Page<CategoryDO> page = categoryMapper.selectPageList(current, size, name, startTime, endTime);

        List<CategoryDO> categoryDOS = page.getRecords();

        List<FindCategoryPageListRspVO> vos = null;

        if (!CollectionUtils.isEmpty(categoryDOS)) {
            vos = categoryDOS.stream()
                    .map(categoryDO -> FindCategoryPageListRspVO.builder()
                            .id(categoryDO.getId())
                            .name(categoryDO.getName())
                            .createTime(categoryDO.getCreateTime())
                            .articlesTotal(categoryDO.getArticlesTotal())
                            .build())
                    .collect(Collectors.toList());
        }

        return PageResponse.success(page, vos);
    }

    @Override
    public Response deleteCategory(DeleteCategoryReqVO deleteCategoryReqVO) {
        Long categoryId = deleteCategoryReqVO.getId();

        ArticleCategoryRelDO articleCategoryRelDO = articleCategoryRelMapper.selectOneByCategoryId(categoryId);

        if (Objects.nonNull(articleCategoryRelDO)) {
            log.warn("==> 次分类下面包含文章,无法删除，categoryId={}", categoryId);
            throw new BizException(ResponseCodeEnum.CATEGORY_CAN_NOT_DELETE);
        }

        // 删除分类
        int count = categoryMapper.deleteById(categoryId);

        return count == 1 ? Response.success() : Response.fail(ResponseCodeEnum.CATEGORY_NOT_EXISTED);
    }

    @Override
    public Response findCategorySelectList() {
        List<CategoryDO> categoryDOS = categoryMapper.selectList(null);

        List<SelectRspVO> selectRspVOS = null;

        if (!CollectionUtils.isEmpty(categoryDOS)) {
            selectRspVOS = categoryDOS.stream()
                    .map(categoryDO -> SelectRspVO.builder()
                            .label(categoryDO.getName())
                            .value(categoryDO.getId())
                            .build())
                    .collect(Collectors.toList());
        }
        return Response.success(selectRspVOS);
    }
}
